/**
 * 合格证打印
 */
import React, { useState, useEffect, useRef } from "react";
import { setCardPrinter, getCardPrinter } from "@/utils/authority";
// import { checkComponentsIsOpen, getAllPrinter, printCard } from "./print.jsx";
import { isEmpty, findIndex, cloneDeep } from "lodash";
//打印方法
import { message, Modal } from "antd";
import { formatAmount } from "@/utils/utils.jsx";
import {
	checkComponentsIsOpen,
	getAllPrinter,
	judgeHasWhichPlatform,
	print,
	printCheckList,
	printVipShop
} from "@/utils/print.jsx";

import request from "@/utils/request";
import { stringify } from "qs";
//合格证批量打印
export async function batchPrintByQualifiedOutbound(params) {
	return request(`/new-wms/outboundorder/batch-print-by-qualified`, {
		method: "Post",
		data: params
	});
}
/**
 * 使用证书的自定义hook，用于处理批量打印合格证的逻辑。
 * @param  outboundNos 需要打印的出货单号(outboundNos)。
 * @returns void
 */
const useCertificate = props => {
	const { outboundNos } = props;
	//打印机数据
	// const [loading, setLoading] = useState(false);
	// 需要打印的合格证数据
	const [certificateList, setCertificateList] = useState([]);
	const [printerOnlineList, setPrinterOnlineList] = useState([]);
	const successCount = useState(0);
	const failedCount = useState(0);
	// const [len, setLen] = useState(0);
	let len = 0;
	// 获取需要批量打印合格证的数据
	const getBatchPrintCofc = async outboundNos => {
		props?.setLoading(true);
		setCertificateList([]);

		const { success, data = [] } = await batchPrintByQualifiedOutbound(outboundNos);

		if (success) {
			props?.setLoading(false);
			const arr = [];
			let i = 0;
			Object.values(data).forEach(skuObj => {
				Object.values(skuObj).forEach(templateList => {
					const item = {
						count: i,
						templateList // item[]
					};
					// console.log("模板 item", cloneDeep(item));
					arr.push(cloneDeep(item));
					i = i + 1;
				});
			});
			// console.log("模板", arr);
			setCertificateList(arr);
		} else {
			console.error("获取打印合格证的数据失败", success, data);
			props?.setLoading(false);
		}
	};
	const printCertificate = async callback => {
		props?.setLoading(true);
		checkComponentsIsOpen([7], async res => {
			if (res.status) {
				// console.log("res.status", res.status);
				// 获取打印模板列表
				getBatchPrintCofc(outboundNos);
				// console.log("certificateList", certificateList);
				len = certificateList.length;
				handleReduceSubmit(0, callback);
			}
			// setTimeout(() => {
			// 	props?.setLoading(false);
			// }, 1000);
		});
	};
	//批量打印
	const handleReduceSubmit = (num, callback) => {
		const item = certificateList[num];
		// console.log("certificateList,num", certificateList, num);
		// console.log("len", len);
		if (len == 0 || isEmpty(item)) {
			props?.setLoading(false);
			Modal.success({
				content: `合格证打印完成,总计${certificateList.length}个,成功${certificateList.length - len}个,失败${len}个`,
				centered: true,
				onOk: () => {
					callback && callback();
				}
			});
		} else {
			// console.log("开始使用打印机打印");
			// console.log("item", item);
			const { templateList } = item;
			const templateName = "合格证_" + num;
			let totalHeight = 0;
			let totalWidth = 0;
			templateList.forEach(e => {
				totalHeight = totalHeight + e.height;
				if (e.width > totalWidth) totalWidth = e.width;
			});
			const data = { templateName, totalWidth, totalHeight, templateList };
			// console.log(templateName, templateList);
			printCard(
				{
					data,
					index: findIndex(printerOnlineList, function (o) {
						return o == getCardPrinter();
					})
				},
				async res => {
					if (res.status) {
						len--;
					}
					handleReduceSubmit(num + 1, callback);
				}
			);
		}
	};

	useEffect(() => {
		getBatchPrintCofc(outboundNos);
		getAllPrinter(value => {
			console.log("getAllPrinter", value);
			setPrinterOnlineList(value);
		});
	}, []);
	return { certificateList, getBatchPrintCofc, printCertificate };
};
/**
 * @desc:合格证打印
 * data: 模板数据 必传
 * goods:商品数据 必传
 * type: 1 打印  2 预览
 * index: 设置打印机（打印机列表索引）
 * callback: 执行回调
 */
// LODOP.SELECT_PRINTER()
export function printCard({ type = 1, data = {}, index }, callback) {
	let LODOP;

	const { templateName, totalWidth, totalHeight, templateList } = data;

	const commonAddStyle = item => {
		/**
   *      "left": "97.28125",
              "top": "5",
              "width": "127",
              "height": "40",
              "fontFamily": "黑体",
              "fontSize": "9"
   */
		Object.keys(item).map(key => {
			if (key == "fontWeight") {
				LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
			} else if (key == "fontStyle") {
				LODOP.SET_PRINT_STYLEA(0, "Italic", 1);
			} else if (key == "textDecoration") {
				LODOP.SET_PRINT_STYLEA(0, "Underline", 1);
			} else {
				LODOP.SET_PRINT_STYLEA(0, key, item[key]);
			}
		});
		LODOP.SET_PRINT_STYLEA(0, "TextNeatRow", true); //允许标点溢出，且英文单词拆开。
	};

	try {
		LODOP = getLodop();
		if (index || index == 0) {
			// LODOP.SET_PRINTER_INDEX(index)
			LODOP.SET_PRINT_MODE("WINDOW_DEFPRINTER", index);
		}
		LODOP.PRINT_INIT(templateName);
		// LODOP.SELECT_PRINTER()
		LODOP.SET_PRINT_PAGESIZE(0, totalWidth * 10, totalHeight * 10, "");
		LODOP.PRINT_INITA("1mm", "0mm", `${totalWidth}mm`, `${totalHeight}mm`, templateName);
		// LODOP.ADD_PRINT_TABLE(0,0,totalWidth*3.8,totalHeight*3.8,'')
		// LODOP.SET_PRINT_STYLEA(0,"PageIndex",1)
		templateList &&
			templateList.map(item => {
				const { top, left, width, height, type, key, prop, fontFamily, fontSize } = item;

				if (top < totalHeight * 3.8) {
					if (item.type == "text") {
						let str = "";
						str += `${key}：${prop || ""};`;

						LODOP.ADD_PRINT_TEXT(top, left, width, height, str);
						commonAddStyle(item);
					} else if (item.type == "customtext") {
						LODOP.ADD_PRINT_TEXT(top, left, width, height, prop);
						commonAddStyle(item);
					} else if (item.type == "barcode" && item.value) {
						if (item.value == "12345678") {
							if (goods["goodsId"]) {
								LODOP.ADD_PRINT_BARCODE(top, left, width, height, "128Auto", goods["goodsId"]);
							}
						} else {
							LODOP.ADD_PRINT_BARCODE(top, left, width, height, "128Auto", item.value);
						}
					} else if (item.type == "qrcode") {
						if (item.value == "#ecSkuId#") {
							LODOP.ADD_PRINT_BARCODE(top, left, width, height, "QRCode", goods["ecSkuId"]);
						} else if (item.value == "#goodsCode#") {
							LODOP.ADD_PRINT_BARCODE(top, left, width, height, "QRCode", goods["goodsCode"]);
						} else {
							LODOP.ADD_PRINT_BARCODE(top, left, width, height, "QRCode", item.value);
						}
						// LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",5);
						// LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","L");
					} else if (item.type == "picture") {
						LODOP.ADD_PRINT_IMAGE(
							top,
							left,
							width,
							height,
							`<img border='0' src=${item.value} width=${width} height=${height} />`
						);
						// LODOP.SET_PRINT_STYLEA(0,"Horient",2);
					}
				}
			});

		// LODOP.PRINT_DESIGN()

		if (type == 1) {
			LODOP.PRINT();
		} else {
			LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", "Full-Page"); //按整页缩放
			// LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW",true);//宽度溢出缩放
			// LODOP.SET_PRINT_MODE("FULL_HEIGHT_FOR_OVERFLOW",true);//高度溢出缩放
			// LODOP.SET_SHOW_MODE("HIDE_PAPER_BOARD",true);//隐藏走纸板
			LODOP.SET_PREVIEW_WINDOW(0, 3, 0, 0, 0, ""); //隐藏工具条，设置适高显示
			LODOP.SET_SHOW_MODE("PREVIEW_IN_BROWSE", true); //预览界面内嵌到页面内
			LODOP.PREVIEW();
		}

		LODOP.On_Return = function () {
			callback && callback({ status: true });
		};
	} catch (err) {
		console.log("catch err", err);
		if (callback) {
			callback({ status: false });
		} else {
			Modal.info({ centered: true, content: "打印出错了" });
		}
	}
}

export default useCertificate;
